import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'function.dart';
import 'model/device_model.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class DrawRecordPage extends StatefulWidget {
  DrawRecordPage(this.device,this.mainColor);
  final DeviceModel device;
  final Color mainColor;
  @override
  _DrawRecordPageState createState() => new _DrawRecordPageState(device);
}

class _DrawRecordPageState extends State<DrawRecordPage> {
  double totalOutcome = 0.0;
  List outcomeArr = [];
  int nextPage = 0;
  int hasData = 2;
  DeviceModel device;
  RefreshController _refreshController = new RefreshController();
  _DrawRecordPageState(this.device) {
    drawRecord(true);
  }
  drawRecord(bool up) async {
    print(this.nextPage);
    var isLogin = await checkLogin(device.sessionid, device.userid);
    bool loginStatus = true;
    if (this.nextPage == -1) {
      _refreshController.sendBack(false, RefreshStatus.noMore);
      return;
    }

    if (!isLogin) {
      Map loginInfo = await doLogin(id: device.id, account: device.account, password: device.password, deviceid: device.device_id, imeiid: device.imeiid);
      if (loginInfo != null) {
        print("重新登录成功");
        device.sessionid = loginInfo['sessionid'];
        device.userid = loginInfo['userid'];
      } else {
        loginStatus = false;
      }
    }
    if (loginStatus) {
      print("登录有效");
      var drawData = await getDrawRecord(device.sessionid, device.userid, this.nextPage);
      if(drawData['iRet']!=0){
        showDialog<Null>(
          context: context,
          builder: (context) {
            return new AlertDialog(
              title: new Text("错误提醒"),
              content: new Text(drawData['sMsg']),
              actions: <Widget>[
                new FlatButton(
                  onPressed: () async {
                    drawRecord(true);
                  },
                  child: new Text(
                    '重试',
                  ),
                ),
                new FlatButton(
                  onPressed: () async {
                    Navigator.of(context).pop();
                  },
                  child: new Text(
                    '返回',
                  ),
                ),
              ],
            );
          },
        );
      }
      this.outcomeArr.addAll(drawData['data']['outcomeArr']);
      if (this.outcomeArr.length > 0) {
        this.hasData = 1;
      } else {
        this.hasData = 0;
      }
      this.totalOutcome = double.parse(drawData['data']['totalOutcome']);
      this.nextPage = drawData['data']['nextPage'];
      if(up==false){
        print(up);
        _refreshController.sendBack(false, RefreshStatus.idle);
      }
      setState(() {});
    } else {
      if(up==false){
        _refreshController.sendBack(false, RefreshStatus.failed);
      }
      showDialog<Null>(
        context: context,
        builder: (context) {
          return new AlertDialog(
            title: new Text("错误提醒"),
            content: new Text("获取提币记录失败，请重试"),
            actions: <Widget>[
              new FlatButton(
                onPressed: () async {
                  drawRecord(true);
                },
                child: new Text(
                  '重试',
                ),
              ),
              new FlatButton(
                onPressed: () async {
                  Navigator.of(context).pop();
                },
                child: new Text(
                  '返回',
                ),
              ),
            ],
          );
        },
      );
    }
  }

  Widget _buildTiles(Map outcome) {
    return new Column(
      children: <Widget>[
        new ListTile(
          title: new Text(
            outcome['originBalance'].toString(),
            style: new TextStyle(fontSize: 22.0, color: widget.mainColor),
          ),
          subtitle: new Text(outcome['updateTime']),
          trailing: new Text(
            outcome['status'] == 2 ? "已到账" : "提币中",
            style: new TextStyle(color: outcome['status'] == 2 ? Colors.green : Colors.black),
          ),
        ),
        Divider(height: 1.0),
      ],
    );
  }

  Widget _pullupBuilder(context, mode) {
    return new ClassicIndicator(
      mode: mode,
      idleText: "上拉加载更多",
      completeText: "加载完成",
      refreshingText: "加载中…",
      releaseText: "松手开始加载",
      noMoreIcon: new Icon(Icons.close),
      noDataText: "到底了",
      idleIcon:new Icon(Icons.arrow_upward),
      refreshingIcon: const CupertinoActivityIndicator(),
      completeIcon: const Icon(Icons.done, size: 32.0, color: Colors.green),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: new CupertinoNavigationBar(
        actionsForegroundColor: Colors.white,
        backgroundColor: widget.mainColor,
        middle: new Text(
          "提币总数：${this.totalOutcome}",
          style: new TextStyle(
            color: Colors.white,
            fontWeight: FontWeight.normal,
          ),
        ),

      ),
      body: this.hasData == 1
          ? new SmartRefresher(
        enablePullDown: false,
        enablePullUp: true,
        onRefresh: drawRecord,
        footerBuilder: _pullupBuilder,
        controller: _refreshController,
        child: new ListView.builder(
          itemCount: outcomeArr.length,
          itemBuilder: (context, i) => _buildTiles(outcomeArr[i]),
        ),
      )
          : this.hasData == 2
          ? new Center(
        child: new CircularProgressIndicator(),
      )
          : new Center(
        child: new Container(
          width: 200.0,
          height: 200.0,
          child: new Column(
            children: <Widget>[
              new Text(
                "暂无提币记录",
                style: new TextStyle(fontSize: 22.0),
              ),
              new FlatButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: new Text("返回")),
            ],
          ),
        ),
      ),
    );
  }
}
